//
//  QuickMealsDB.m
//  QuickMeals2_iOS
//
//  Created by CAMILO ANTONIO RODRIGUEZ GAVIRIA on 28/09/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "QuickMealsDB.h"
#import "Comida.h"
#import "Restaurante.h"


@implementation QuickMealsDB

@synthesize result;

/*
 * Los métodos:
 * applicationDidFinishLaunching
 * checkAndCreateDataBase
 *
 * Fueron implementados por:
 * http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
 * 
 * Claro está que fueron editados para cumplir con los requisitos de la aplicación y su contexto.
 */
- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// Setup some globals
	databaseName = @"QMDatabase.db";
	
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
	// Execute the "checkAndCreateDatabase" function
	[self checkAndCreateDatabase];
}

- (void)dealloc {
	[super dealloc];
}

-(void) checkAndCreateDatabase{
	// Check if the SQL database has already been saved to the users phone, if not then copy it over
	BOOL success;
	
	// Create a FileManager object, we will use this to check the status
	// of the database and to copy it over if required
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Check if the database has already been created in the users filesystem
	success = [fileManager fileExistsAtPath:databasePath];
	
	// If the database already exists then return without doing anything
	if(success) return;
	
	// If not then proceed to copy the database from the application to the users filesystem
	
	// Get the path to the database in the application package
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copy the database from the package to the users filesystem
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}
/**
 * Método que retorna todas las comidas de la base de datos
 * 
 * @param meals Las comidas existentes en la base de datos
 */
-(void) getMeals:(NSMutableArray *)meals{
	database = [self openDatabase];
	const char *sqlStatement = "SELECT * FROM Comidas";
	sqlite3_stmt * compiledStatement;
	
	if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
		while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
			
			NSString * nombre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
			int tiempo = sqlite3_column_int(compiledStatement, 2);
			double precio = sqlite3_column_double (compiledStatement, 3);
			int calorias = sqlite3_column_int (compiledStatement, 4);
			
			Comida * comida = [comida createMeal:nombre calories:calorias price:precio prepTime:tiempo];
			[meals addObject:comida];
		}
	}
	sqlite3_close(database);
}
/**
* Método que retorna todos los restaurantes de la base de datos
* 
* @param restaurants Los restaurantes existentes en la base de datos
*/
-(void) getRestaurants: (NSMutableArray *)restaurants{
	database = [self openDatabase];
	const char * sqlStatement = "SELECT * FROM Restaurantes";
	sqlite3_stmt * compiledStatement;
	
	if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
		while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
			NSString * nombre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
			int telefono = sqlite3_column_int(compiledStatement, 1);
			NSString * correo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
			Restaurante * res = [res createRestaurant:nombre number:telefono email:correo];
			[restaurants addObject:res];
		}
	}
	sqlite3_close(database);
}
/**
 * Método que retorna todos los productos de una categoria perteneciente a un restaurante
 * 
 * @param restaurant El restaurante a consultar
 * @param category La categoria de los productos
 * @return Los productos de esa categoria, pertenecientes al restaurante
 */
-(NSMutableArray *) getResourcesByCategoryAndRestaurants: (NSString *)restaurant category:(NSString *)category{
	NSMutableArray * products = [[NSMutableArray alloc] init];
	database = [self openDatabase];
	const char * res = [restaurant cStringUsingEncoding:NSUTF8StringEncoding];
	const char * cat = [category cStringUsingEncoding:NSUTF8StringEncoding];
	const char * sqlStatement = "SELECT Producto, Precio, TiempoPreparacion FROM Menu WHERE Restaurante = ? AND Categoria = ?";
	sqlite3_stmt * compiledStatement;
	if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK){
		sqlite3_bind_text(compiledStatement, 1, res, -1, SQLITE_STATIC);
		sqlite3_bind_text(compiledStatement, 2, cat, -1, SQLITE_STATIC);
		while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
			NSString * nombre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
			int precio = sqlite3_column_int(compiledStatement, 1);
			int tiempo = sqlite3_column_int(compiledStatement, 2);
			Comida * comida = [comida createMeal:nombre price:precio prepTime:tiempo];
			[products addObject:comida];
		}
	}
	sqlite3_close(database);
	return products;
}
/**
 * Método que busca un producto en la tabla Menu
 * 
 * @param product El nombre del producto a buscar
 * @param restaurant El restaurante que vende el producto
 * @return El producto encontrado, o null en caso de que no exista
 */
-(Comida *) searchMealByNameAndRestaurant:(NSString *)product restaurant:(NSString *)restaurant{
	database = [self openDatabase];
	const char * prod = [product cStringUsingEncoding:NSUTF8StringEncoding];
	const char * res = [restaurant cStringUsingEncoding:NSUTF8StringEncoding];
	const char * sqlStatement = "SELECT * FROM Menu WHERE Producto = ? AND Restaurante = ?";
	sqlite3_stmt * compiledStatement;
	
	if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
		sqlite3_bind_text(compiledStatement, 1, prod, -1, SQLITE_STATIC);
		sqlite3_bind_text(compiledStatement, 2, res, -1, SQLITE_STATIC);
		while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
			NSString * categoria = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
			NSString * nombre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
			int precio = sqlite3_column_int(compiledStatement, 3);
			int tiempo = sqlite3_column_int(compiledStatement, 4);
			sqlite3_close(database);
			Comida *comida = [comida createMeal:nombre category:categoria price:precio prepTime:tiempo];
			return comida;
		}
	}
	return nil;
}
/**
 * Método que abre la base de datos
 * 
 * @return true si se abrió correctamente, false de lo contrario
 */
- (sqlite3 *) openDatabase{
	sqlite3 *newDBConnection;
	NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString * documentsDirectory= [paths objectAtIndex:0];
	NSString * path = [documentsDirectory stringByAppendingFormat:@"QMDatabase.db"];
	
	if (sqlite3_open([path UTF8String], &newDBConnection) == SQLITE_OK) {
		return	newDBConnection;
	}
	return nil;
}

@end
